﻿Imports System.Runtime.CompilerServices

Namespace Packaging
    ''' <summary>
    ''' Extension metods to Package managing.
    ''' </summary>
    ''' <remarks></remarks>

    Public Module Extensions
        ''' <summary>
        ''' Creates an extension package from a CintieFramework Script
        ''' </summary>
        ''' <param name="File">(This file) the script to convert in a package </param>
        ''' <param name="OutputFile">The result file</param>
        ''' <remarks></remarks>
        <Extension()> _
        Public Sub CreatePackage(ByVal File As IO.FileInfo, ByVal OutputFile As String)
            Using Zip As New Ionic.Zip.ZipFile
                Zip.AddFile(File.FullName, "//") 'Add the main script File
                Zip.AddDirectory(File.FullName & ".storage", File.Name & ".storage") 'Add the storage directory
                Zip.Save(OutputFile)
            End Using
        End Sub

        ''' <summary>
        ''' Unzip the current file to the selected directory
        ''' </summary>
        ''' <param name="File">The file to unzip</param>
        ''' <param name="OutputDir">The directory that will contains the unzipped files</param>
        ''' <remarks></remarks>
        <Extension()> _
        Public Function Unpackage(ByVal File As IO.FileInfo, ByVal OutputDir As String) As CintieFramework.Script
            Dim ZipFile As String = File.FullName
            Console.WriteLine("Extracting file {0} to {1}", ZipFile, OutputDir)

            Dim MainScriptFile As String = ""

            Using zip1 As Ionic.Zip.ZipFile = Ionic.Zip.ZipFile.Read(ZipFile)
                'Add the handler here
                Dim Entry As Ionic.Zip.ZipEntry

                For Each Entry In zip1
                    Entry.Extract(OutputDir, Ionic.Zip.ExtractExistingFileAction.OverwriteSilently)
                    Dim _fi As New IO.FileInfo(Entry.FileName)
                    If _fi.Extension = ".cf" Then
                        MainScriptFile = String.Format("{0}\{1}", OutputDir, _fi.Name)
                    End If
                Next

                'Throw an exception if theres no CintieFramework script file
                If MainScriptFile = "" Then
                    Throw New Exceptions.NoScriptFileFound(File.Name)
                Else
                    Return New CintieFramework.Script(New IO.FileInfo(MainScriptFile))
                End If
            End Using
        End Function
    End Module


    Namespace Exceptions
        Public Class NoScriptFileFound
            Inherits System.Exception

            Public Sub New(ByVal Message As String)
                MyBase.New(Message)
            End Sub

            Public Sub New(ByVal File As IO.FileInfo)

                MyBase.New(String.Format("Not found script file in the {0} package"))

            End Sub
        End Class
    End Namespace

End Namespace
